/*-----------------------------------------------------------------------------
 * 作者:长春驿枫(YiFeng)
 * http://www.seeadmin.com/
 * version:1.0  , 时间：2015-4-20
 * Ladder内部js库的核心基本模块
 * 1)依赖于Jquery
 * 2)依赖于severic路径配置
 * @class Ladder
 -----------------------------------------------------------------------------*/
;!(function(){
	var isHaveJq=(function(){
	    var script = document.getElementsByTagName("script");
	    var isloadjquery=false;
	    for (var i = 0; i < script.length; i++) {
	        var src = script[i].src;
	        if (/\w*jquery[\.\w-]*.js($|(\?[\w\W]*)$)/.test(src)) {
	            isloadjquery=true;
	        }
	    }
	    return isloadjquery;
	})();
	if(window.Ladder)return;
	console.log("加载主模块");
	var __functionForCore=function (store,laytpl) {
    /**
     * @class YFLib.core
     * @extends YFLib
     */
    /**
     * 前置全局初始化执行
     * @private
     * @returns {string|string}
     */
    function fetchBasicURL() {
    	var $require=$("script[src*='require.js'][data-base]");
    	if ($require.length == 0){
    	    //没有配置路由功能
    		if(!window.URLS){
    		    URLS={};
                var js=document.scripts;
                URLS.URL_BasicURL=js[js.length-1].src.substring(0,js[js.length-1].src.lastIndexOf("/")+1);
    		    return URLS.URL_BasicURL;
            }
	        if(URLS.URL_BasicURL&&URLS.URL_BasicURL.indexOf("{root}")==-1){
	            return URLS.URL_BasicURL;
	        }
	        var sign = "/";
	        if (URLS.URL_Root) sign = URLS.URL_Root;
	        var url = window.location.href;
	        var index = url.indexOf(sign, (location.protocol+location.hostname).length);
	        var basepath = url.substring(0, index+sign.length);
	        URLS.URL_Root=basepath;
	        URLS.URL_BasicURL=URLS.URL_BasicURL.replace("{root}", basepath);
	        return URLS.URL_BasicURL;
    	}else{
    		return $require.attr("data-base");
    	}

    }
    window.Ladder={
        /**
         * 创建子命名空间,第一次进入返回空对象
         * @param ns ｛String｝空间名称
         * @returns {Object}
         */
        NS:function(ns) {
            if (!ns || !ns.length) {
                return null;
            }
            var levels = ns.split(".");
            var nsobj = Ladder;
            for (var i=(levels[0] == "Ladder") ? 1 : 0; i<levels.length; ++i) {
                nsobj[levels[i]] = nsobj[levels[i]] || {};
                nsobj = nsobj[levels[i]];
            }
            return nsobj;
        },
        /**
         * 获取对象类型名
         * ["Array", "Boolean", "Date", "Number", "Object", "RegExp", "String", "Window", "HTMLDocument"]
         * @param object
         * @returns {String} 类型的名称
         */
        getType:function(object){
            return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
        },
        /**
         * 用来判断对象类型
         * @param {Object} object
         * @param {String} typeStr
         * @returns {boolean}
         */
        is:function(object,typeStr){
            return this.getType(object)==typeStr;
        },
        /**
         *返回字符串
         * @param data
         * @param {String} splitstr 分割字符
         * @param {String} wrapstr  包裹字符
         * @return  {String}
         */
        toString:function(data,splitstr,wrapstr,name){
            if(data==undefined)return;
            var _type=Ladder.getType(data);
            var re_t="";
            if(splitstr==undefined)splitstr="";
            if(wrapstr==undefined)wrapstr="";
            switch (_type){
                case "String":
                    break;
                case "Array":
                    for(var i=0;i<data.length;i++){
                        var nodeData=data[i];
                        if(nodeData==undefined)continue;
                        var _t=Ladder.getType(nodeData);

                        if(_t=="Object"){
                            if(name){
                                re_t+=wrapstr+(nodeData[name]?nodeData[name]:"")+wrapstr+splitstr;
                            }else{
                                for(var propname in nodeData){
                                    re_t+=wrapstr+(nodeData[propname]?nodeData[propname]:"")+wrapstr+splitstr;
                                    break;
                                }
                            }
                        }else{
                            re_t+=wrapstr+data[i]+wrapstr+splitstr;
                        }

                    }
                    if(re_t.length>splitstr.length)return re_t.substr(0,re_t.length-splitstr.length);
                    return re_t;
                default :
                    break;

            }
        },
        /**
         * 判断文本的长度
         * @param text
         * @returns {number}
         */
        textLength:function(text){
            var intLength=0;
            for (var i=0;i<text.length;i++){
                if ((text.charCodeAt(i) < 0) || (text.charCodeAt(i) > 255)){
                    intLength=intLength+2;
                }else{
                    intLength=intLength+1;
                }
            }
            return intLength
        },
        /**
         * 获取浏览器版本
         * @returns {Array|{index: number, input: string}}
         */
        browserversion:function(){
            var agent = navigator.userAgent.toLowerCase() ;
            var regStr_ie = /msie [\d.]+;/gi ;
            var regStr_ff = /firefox\/[\d.]+/gi;
            var regStr_chrome = /chrome\/[\d.]+/gi ;
            var regStr_saf = /safari\/[\d.]+/gi ;
            //IE
            if(agent.indexOf("msie") > 0)return agent.match(regStr_ie)[0] ;
            //firefox
            if(agent.indexOf("firefox") > 0)return agent.match(regStr_ff)[0] ;
            //Chrome
            if(agent.indexOf("chrome") > 0)return agent.match(regStr_chrome)[0] ;
            //Safari
            if(agent.indexOf("safari") > 0 && agent.indexOf("chrome") < 0) return agent.match(regStr_saf)[0];
        },
        /**
         * 生成随机数
         * @param num [num=4]
         * @param type [type=number]
         * @returns {String}
         */
        random:function(num,type) {
            if (!num)num = 4;
            if(!type || type.toLowerCase()=='number')
                return Math.floor(Math.random() * Math.pow(10,num));
            if(type&&type.toLowerCase()=='string'){
                var s='';
                for(var i=0;i<num;++i){
                    s+=String.fromCharCode(65 +Math.random()*26);
                }
                return s;
            }
        },
        /**
         * 加载进度条
         */
        progressBar:function(el,msg){
            var uuid=Ladder.uuid(10);
            if(!msg)msg="正在运行处理中";
            if(el==undefined){//这是window整个界面
                if($(".yui-cover").length>0)return;
                $("<div id='cover"+uuid+"' class='yui-cover'></div><div class='yui-loading' id='loadimg"+uuid+"'><span>"+msg+"</span></div>").appendTo('body');
                var w=$(window).outerWidth(),h=$(window).outerHeight();
                $("#cover"+uuid).css({'width':w,'height':h,'position':'absolute','background':'#000','z-index':999999999,'left':0,'top':0}).fadeTo('slow',0.6);
                $('#loadimg'+uuid).css({
                    'position':'absolute',
                    'background':'url('+Ladder.BasicURL+'/css/images/loading1.gif) no-repeat center center',
                    'background-color':"transparent",
                    'z-index':9999999999,'width':'110px','height':'64px','left':(w-110)/2,'top':((h-64)/2-10)}
                ).find('span').css({
                    'position':'absolute','left':0,'bottom':'-25px',color:"#FFF",
                    'width':110,'display':'block','height':40,'text-align':'center'
                });
            }else{
                var $el=$(el);
                if($el.length<1||$el.is(":hidden"))return false;
                var offset=$el.offset();
                $("<div class='yui-cover' id='cover"+uuid+"'><div class='yui-loading' id='loadimg"+uuid+"'></div></div>").appendTo('body');
                var w=$el.outerWidth(),h=$el.outerHeight();
                $("#cover"+uuid).css({
                    'width':w+"px",'height':h+"px",'position':'absolute','background':'transparent',
                    'z-index':9999,'left':offset.left,'top':offset.top
                }).fadeTo('slow',0.8);
                $('#loadimg'+uuid).css({
                    'position':'absolute',
                    'background':'url('+Ladder.BasicURL+'/css/images/loading1.gif) no-repeat center center',
                    'z-index':10000,'width':'110px','height':'64px','left':(w-110)/2,'top':((h-64)/2)-50}
                );
            }
        },
        /**
         * 停止进度条
         */
        stopProgress:function(uuid){
            if(uuid){
                $('#cover'+uuid).remove();
                $('#loadimg'+uuid).remove();
            }else{
                $('.yui-cover').remove();
                $('.yui-loading').remove();
            }

        },
        /**
         * 获取图片的大小
         */
        getImgWh:function(url, callback) {
            var width, height, intervalId, check, div, img = new Image(),
                body = document.body;
            img.src = url;

            //从缓存中读取
            if (img.complete) {
                return callback(img.width, img.height);
            };

            //通过占位提前获取图片头部数据
            if (body) {
                div = document.createElement('div');
                div.style.cssText = 'visibility:hidden;position:absolute;left:0;top:0;width:1px;height:1px;overflow:hidden';
                div.appendChild(img)
                body.appendChild(div);
                width = img.offsetWidth;
                height = img.offsetHeight;
                check = function() {
                    if (img.offsetWidth !== width || img.offsetHeight !== height) {
                        clearInterval(intervalId);
                        callback(img.offsetWidth, img.clientHeight);
                        img.onload = null;
                        div.innerHTML = '';
                        div.parentNode.removeChild(div);
                    };
                };
                intervalId = setInterval(check, 150);
            };
            // 加载完毕后方式获取
            img.onload = function() {
                callback(img.width, img.height);
                img.onload = img.onerror = null;
                clearInterval(intervalId);
                body && img.parentNode.removeChild(img);
            };
        },
        /**
         * 全屏
         */
        fullscreen:function(){
            //此方法无效
            var docElm = document.documentElement;
            if (docElm.requestFullscreen) {
                docElm.requestFullscreen();
            }
            else if (docElm.mozRequestFullScreen) {
                docElm.mozRequestFullScreen();
            }
            else if (docElm.webkitRequestFullScreen) {
                docElm.webkitRequestFullScreen();
            }
        },
        /**
         * 退出全屏
         */
        exitFullscreen:function(){
            //此方法无效
            if (document.exitFullscreen) {
                document.exitFullscreen();
            }
            else if (document.mozCancelFullScreen) {
                document.mozCancelFullScreen();
            }
            else if (document.webkitCancelFullScreen) {
                document.webkitCancelFullScreen();
            }
        },
        //IE全屏
        fullscreenIE:function(){
            //if(/msie/.test(navigator.userAgent.toLowerCase()))
            if($.browser.msie){
                //window.open(document.location, 'big', 'fullscreen=yes');
                //window.close();
                var  wsh =  new  ActiveXObject("WScript.Shell");
                wsh.sendKeys("{F11}");
            }
        },
        /**
         * 设置和获取window的高度和宽度
         * @param rw 读写位，默认是读
         * @returns {Object} 对象为：s{w:x,h:y}
         */
        winWH:function(rw){
            if(rw){
                var winWH={w:$(window).width(),h:$(window).height()};
                $(document.body).data("winWH",winWH);
                return winWH;
            }else{
                var winWH=$(document.body).data("winWH");
                if (winWH) return winWH;
                else return Ladder.winWH(1);
            }
        },
        /**
         * 把文本转换成json对象
         * 和JSON.parse解析不同，此方法较为粗糙
         * @param strdata 文本
         * @param filter 是否过滤 定义符和注释
         * @returns {Object}
         */
        toJSON:function(strdata,filter){
            if(strdata==undefined)return false;
            if(strdata===null)return null;
            var _type=Ladder.getType(strdata);
            if(_type=='Object' || _type=="Array" || _type=="Function" )return strdata;
            if(Ladder.getType(strdata)!="String")return new Object();
            if(filter){
                if(/\/\*[\w\W\r\n]*?\*\//gmi.test(strdata)){
                    strdata=strdata.replace(/\/\*[\w\W\r\n]*?\*\//gmi,'');
                }
                if(/^\s*(var)\s*\w*\s*=\s*(\{|\[)/.test(strdata)){
                    strdata=strdata.replace(/^\s*(var)\s*\w*\s*=/,'');
                }
            }
            if(Ladder.getType(strdata)=='String' && /(^\{[\s\S]*\}$)|(^\[[\s\S]*\]$)/.test(strdata))
                return eval("("+strdata+")");
            else return strdata;
        },
        /**
         * 阻止事件冒泡
         * @param event
         */
        stopPropagation: function (event) {
            var e=window.event || event;
            if(e.stopPropagation){
                e.stopPropagation();
            }else{
                e.cancelBubble = true;
            }
        },
        /**
         * 格式化日期
         * @param ds {Date/String} [ds=new Date()]
         * @param format {String} [format="yyyy-MM-dd hh:mm:ss"] 文本格式
         * @param offset {int} 时间的偏移量{String}
         * @returns {String}
         */
        dateFormat: function (ds, format,offset) {
            if (ds == undefined)ds = new Date();
            if(offset==undefined)offset=0;
            var thisdate=false;
            if(!format)format="yyyy-MM-dd hh:mm:ss";
            if(Ladder.getType(ds)=="Date"){
                thisdate=ds;
            }
            if(Ladder.getType(ds)=="String"){
                if(/00:00:00\.0$/.test(ds))
                    if(/\d\.0$/.test(ds))ds=ds.substr(0,ds.length-2);
                var ddddd=new Date(ds.replace(/-/g,"/"));
                if(ddddd){
                    thisdate=ddddd;
                }
            }
            if(!thisdate)return ds;
            //时间的整数值
            var _time=thisdate.valueOf()+ offset * 24 * 60 * 60 * 1000;
            thisdate=new Date(_time);
            var o = {
                "M+" : thisdate.getMonth()+1, //month
                "d+" : thisdate.getDate(), //day
                "h+" : thisdate.getHours(), //hour
                "m+" : thisdate.getMinutes(), //minute
                "s+" : thisdate.getSeconds(), //second
                "q+" : Math.floor((thisdate.getMonth()+3)/3), //quarter
                "S" : thisdate.getMilliseconds() //millisecond
            };
            if(/(y+)/i.test(format)) {
                format = format.replace(RegExp.$1, (thisdate.getFullYear()+"").substr(4 - RegExp.$1.length));
            }
            for(var k in o) {
                if(new RegExp("("+ k +")").test(format)) {
                    format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
                }
            }
            return format;

        },
        /**
         * 生成UUID
         * @param {number} len 长度
         * @param {number} radix 进制
         * @returns {string}
         */
        uuid:function(len, radix){
            var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
            var uuid = [], i;
            radix = radix || chars.length;
            if (len) {
                // Compact form
                for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
            } else {
                // rfc4122, version 4 form
                var r;

                // rfc4122 requires these characters
                uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
                uuid[14] = '4';
                // Fill in random data.  At i==19 set the high bits of clock sequence as
                // per rfc4122, sec. 4.1.5
                for (i = 0; i < 36; i++) {
                    if (!uuid[i]) {
                        r = 0 | Math.random()*16;
                        uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                    }
                }
            }
            return uuid.join('');
        },
        timecode:function(){
            return  (new Date()).valueOf();
        },
        /**
         * 从请求路径获取参数值
         * @param name
         * @param ignorecase
         * @returns {*}
         */
        getRequestParam:function(name, ignorecase){
            var linkstr=(location.href)+"&";
            if(ignorecase){
                name=name.toLowerCase();
                linkstr=linkstr.toLowerCase();
            }
            var n_length=name.length;
            var s_in=0;
            if((s_in=linkstr.indexOf(name+"="))<0){
                return false;
            }else{
                var i_last=linkstr.indexOf("&",s_in+n_length+1);
                if(i_last>0){
                    var p_value=linkstr.substring(s_in+n_length+1,i_last);
                    return p_value;
                }else{
                    return false;
                }
            }
        },
        /**
         * @property 基本路径
         */
        BasicURL:fetchBasicURL(),
        ServerUrl:URLS.URL_Server?URLS.URL_Server:URLS.URL_Root,
        /**
         * 获取当前的Cookie
         * @param {String} name 键名
         * @returns {String}
         */
        getCookie:function(name){
            var cookieStr=document.cookie;
            var regText= new RegExp("[;=&]?"+name+"=([^&^;]*)([;&]|$)");
            if(regText.test(cookieStr)){
                var matchText=cookieStr.match(regText);
                if(matchText.length>1)return matchText[1];
            }
            return false;
        },
        /**
         * 向浏览器中储存Store
         * @param {String} key store的key
         * @param {object} val store的值
         */
        setStore:function(key,val){
            if(Ladder.store){
                var type=Ladder.getType(val);
                if(type==="String"){
                    Ladder.store.set(key,val);
                    return;
                }
                if(/(Object)|(Array)/.test(type)){
                    if(val instanceof $){
                        val=JSON.stringify(val.html());
                    }else{
                        val=JSON.stringify(val);
                    }
                }
                else if(/Date/.test(type)){
                    val=Ladder.dateFormat(val);
                }
                //如果是原生dom对象，置空
                else if(/(Window)|(HTMLDocument)/.test(type)){
                    val="";
                }
                Ladder.store.set(key,val);
            }
        },
        /**
         * 从浏览器中获取Store
         * @param {String} key Store的key
         * @returns {*|Object}
         */
        getStore:function(key,serializable){
            var val=Ladder.store.get(key);
            if(serializable==undefined||serializable===true){
                return Ladder.toJSON(val);
            }
            return val;
        },
        /**
         * 导出Excel表格（table元素）
         * @param el
         * @param url
         */
        exportToExcel:function(el,url) {
            if (!el) return;
            if (!url) url = Ladder.Service.parseUrl(URLS.URL_ExportToExcel);
            var $table=$(el);
            if($table.length<1)return;
            var data=[];
            $table.find("tr").each(function(){
                data.push([]);
            });
            $table.find("tr").each(function(index){
                var $tr = $(this);
                var col = getColIndex(index, 0);
                $tr.find("td,th").each(function(){
                    var $td=$(this);
                    var colspan=$td.prop("colspan");
                    var rowspan=$td.prop("rowspan");
                    col = getColIndex(index, col);
                    for(var i=0;i<rowspan;i++){
                        if(i>0){
                            data[index + i][col] = { value: $td.text(), col: 0, row: 0 }
                        }else{
                            data[index + i][col] = { value: $td.text(), col: colspan, row: rowspan }
                        }
                    }
                    for(var i=colspan-1;i>0;i--){
                        data[index][col + i] = { value: $td.text(), col: 0, row: 0 };
                    }
                    col+=colspan;
                });
            });
            //获取列号
            function getColIndex(x,y){
                if(data[x]==undefined) return 0;
                while(data[x][y]!=undefined)y++;
                return y;
            }
            //如果没有iframe进行创建，id固定够长，防止污染
            if($("iframe#Laddertempexporttable201620152014").length<1){
                $("<iframe id='Laddertempexporttable201620152014' style='display: none;'></iframe>").appendTo('body');
            }
            //iframe dom对象
            var $frame=$("iframe#Laddertempexporttable201620152014")[0].contentDocument;
            $frame.open();
            $frame.write('<form method="post" action="" id="exportForm"><input type="hidden" id="model" name="model"></form>');
            $frame.close();
            var $form=$("#exportForm",$frame);
            $form.attr("action",url);
            $form.find("#model").val(JSON.stringify({columnModel:data}));
            $form.submit();
            $frame.close();
        },
        dom:function(id){
            if(!id)return;
            return document.getElementById(id);
        },
        layout:function(el){
            var widgets=undefined;
            if(el){
                widgets=$(el);
                widgets.add($(el).find("[layoutH]"));
            }
            else widgets= $("[layoutH]");
            widgets.each(function(){
                var $this=$(this);
                var v=$this.attr("layoutH");
                var offset=$this.offset();
                if(v==undefined)return;
                if(/\d*/.test(v)||/\d*px/.test(v)){
                    v=v.replace("px","")*1;
                    $this.height($(window).height()-offset.top-v);
                    return;
                }
                if(/^\s*(\.|#)[\w\W]*/.test(v)){
                    $this.height($(v).offset().top-offset.top);
                    return;
                }
                else{
                    $this.height($this.parent().offset().top-offset.top);
                    return;
                }
            });
        },
        data:function(data,key){
            if(Ladder.getType(data)=="Object"&&data.version=="Ladder"){
                if(key)data.get(key);
                return data;
            }
            var obj={
                version:"Ladder",
                data:data,
                getV:function(d,name){
                    if(d==undefined)d=this.data;
                    if(d===null||d===undefined)return null;
                    if(d.hasOwnProperty(name)){
                        return d[name];
                    }else{
                        for(var p in d){
                            if(p.toLowerCase()==name.toLowerCase())return d[p];
                        }
                    }
                    return null;
                },
                get:function(name){
                    if(name==undefined)return this.data;
                    if(this.data===null||this.data===undefined)return null;
                    var ntype = Ladder.getType(name);
                    var dtype = Ladder.getType(this.data);
                    if(ntype=="String"&&dtype=="Object"){
                        //a
                        if(/^[\w_]*$/.test(name)){
                            return this.getV(this.data,name);
                        }
                        //a.b.c
                        if(/^[\w_]*\./.test(name)){
                            var ns=name.split(".");
                            var per=this.data;
                            for(var i= 0,count=ns.length;i<count;i++){
                                per = this.getV(per,ns[i]);
                                if(per===null)return null;
                                if(i<count-1){
                                    per=Ladder.toJSON(per);
                                }
                            }
                            return per;
                        }
                        //a/b/c
                        if(/^[\w_]*\//.test(name)){
                            var ns=name.split("/");
                            var per=this.data;
                            for(var i= 0,count=ns.length;i<count;i++){
                                per = this.getV(per,ns[i]);
                                if(per===null)return null;
                            }
                            return per;
                        }
                        //*.a
                        if(/^\*\.[\w_]*$/.test(name)){

                            function getObject(d,name){
                                if(d===null||d===undefined)return null;
                                if(Ladder.getType(d)!="Object")return null;
                                for(var p in d){
                                    if(p.toLowerCase()==name.toLowerCase()){
                                        return d[p];
                                    }
                                    var v=getObject(d[p],name);
                                    if(v!=null)return v;
                                }
                                return null;
                            }

                            return getObject(this.data,name.replace("*.",""));
                        }
                    }
                    return null;
                },
                set:function(key,value){
                    if(key==undefined)return this.data;
                    if(this.data===null||this.data===undefined||Ladder.getType(this.data)!="Object")return this.data;
                    var ks = key.split(/\/|\./);
                    var size=ks.length;
                    if(size>1&&ks[0]!="*"){
                        var d=this.data;
                        ks.slice(0,-1).forEach(function(item){
                            if(d[item]==undefined||d[item]==null||Ladder.getType(d[item])!="Object")d[item]={};
                            d=d[item];
                        });
                        var glass = eval("this.data."+Ladder.toString(ks.slice(0,-1),"."));
                        glass[ks[ks.length-1]]=value;
                    }else{
                        data[ks[size-1]]=value;
                    }
                    return this.data;
                }
            };
            if(key!=undefined)return obj.get(key);
            return obj;
        },
        timestamp:function() {
            return Math.round(new Date().getTime() / 1000);
        },
        md5:function(v){
            var md5=CryptoJS.MD5(v);
            if(md5)return md5.toString();
        },
        /**
         * 合并数组
         * @param {} ar 数组1
         * @param {} br 数组2
         * @param {} pname 过滤索引
         * @returns {}
         */
        mergeArray:function(ar,br,pname) {
            if ((!ar||ar.length<1)&&(!br||br.length<1))return [];
            var temp= {_list_:[],length:0}
            push(ar);
            push(br);
            function push(data) {
                if (!data)return;
                data.forEach(function(item) {
                    switch (Ladder.getType(item)){
                        case "Object":
                            if(pname&&item[pname]){
                                if(!temp.hasOwnProperty(item[pname])){
                                    temp[item[pname]]=1;
                                    temp._list_.push(item);
                                    temp.length++;
                                }
                            }else{
                                temp._list_.push(item);
                                temp.length++;
                            }
                            break;
                        case "Number":
                            item=item+"";
                        case "String":
                            if(item&&!temp.hasOwnProperty(item)){
                                temp[item]=1;
                                temp._list_.push(item);
                                temp.length++;
                            }
                            break;

                    }
                });
            }
            return temp._list_;
        },
        /***
         * 获取元素树z-index的最大值
         * @param parent 父级元素
         * @param max 最大值
         * @returns {int}
         */
        getMaxZ:function(parent,max){
            if(!max)max=0;
            var $parent=$(parent);
            if($parent.length<1 || $parent.is(document.body)){
                return max;
            }
            var zindex = $parent.css("z-index");
            zindex=zindex>max?zindex:max;
            return Ladder.getMaxZ($parent.parent(),zindex);
        },
        clone:function(data){
            switch (Ladder.getType(data)){
                case "Undefined":
                case "Null":
                    return undefined;
                case "Object":
                    var newobj={};
                    for(var p in data)newobj[p]=Ladder.clone(data[p]);
                    return newobj;
                default:
                    return data;
            }
        },
        include : function(file){
            if(!file)return;
            var files = typeof file == "string" ? [file] : file;
            for (var i = 0; i < files.length; i++){
                var name = files[i].replace(/^\s|\s$/g, "");
                var att = name.split('.');
                var ext = att[att.length - 1].toLowerCase();
                var isCSS = /^css/.test(ext);
                var tag = isCSS ? "link" : "script";
//              var attr = isCSS ? " type='text/css' rel='stylesheet' " : " language='javascript' type='text/javascript' ";
//              var link = (isCSS ? "href" : "src") + "='"+ name + "'";
                //重复性判断
                var repeatSelector=(isCSS ? "href" : "src") + "$='"+ name.replace(/^[\w\W]*\//,"") + "'"
                //if ($(tag + "[" + link + "]").length == 0){
                if ($(tag + "[" + repeatSelector + "]").length == 0){
                	var dom=undefined;
                	if(isCSS){
                		dom=document.createElement("link");
                		dom.type='text/css';
                		dom.rel='stylesheet';
                		dom.href=name;
                	}else{
                		dom = document.createElement("script"); 
						dom.src = name; 
						dom.type = "text/javascript"; 
                	}
					document.getElementsByTagName("head")[0].appendChild(dom); 
                	//$("head").append("<" + tag + attr + link + "></" + tag + ">");
                    //document.write("<" + tag + attr + link + "></" + tag + ">");
                }
            }
        },
        animate:function(el,name,time,action){
            el=$(el);
            if($(el).length<1)return;
            el.addClass(name);
            setTimeout(function(){
                el.removeClass(name);
                if(action)action(el);
            },time);
        },
        /***
         * 跳页
         * @param config
         */
        gotoPage:function(config){
            Ladder.Service.gotoPage(config);
        },
        getRequestInfo:function(keep){
            Ladder.Service.getRequestInfo(keep);
        }
    };
    /**
     * 与后端的异步交互
     * eg: webajax(URLS.URL_Querydata,data,function(return){});
     *     可写参数：1.url：与后台交互的接口路径
     *              2.data：与后台交互的数据
     *              3.function：回调函数
     * @returns {*}
     */
    $.webajax = function() {
        //默认变量
        function empty() {}
        //默认的情况的参数
        var def = {
            type: "POST",
            dataType: "json",
            timeout: 0,
            onBefore: empty,
            onComplete: empty,
            requestType: 'YF', //安装驿枫定义的数据接口进行访问和使用
            async: false,
            assert:true,
            hasErrorFun:true, //是否含有错误处理函数
            ssl:false
        };
        var url, data, callback, errorfun, opt;
        var strsize = 0, objsize = 0, funsize = 0;
        if (arguments.length < 1) return;
        //对argumnents进行解析
        for (var i = 0; i < arguments.length; ++i) {
            var atype = Ladder.getType(arguments[i]);//获取参数类型
            if (atype == "String") {
                if (++strsize == 1) {//第一次出现字符串形式的参数，默认为URL
                    url = arguments[i];
                }
                if (strsize > 1) {
                    //非第一次出现的字符串形式的参数判断组成
                    if (/^(json)|(xml)|(jsonp)|(script)|(html)$/gi.test(arguments[i])) {
                        def.dataType = arguments[i]+"_@_";//改变数据类型
                        continue;
                    } else if (/^(post)|(get)|(put)|(delete)$/gi.test(arguments[i])) {
                        def.type = arguments[i];//改变通讯方式
                        continue;
                    }else if(/^(private)|(ssl)$/gi.test(arguments[i])){
                        def.ssl=true;
                        continue;
                    }else if (/=/.test(arguments[i])) {
                        data = arguments[i];
                        continue;
                    } else {
                        def.requestType = arguments[i];//改变请求方式
                        continue;
                    }
                }
            } else if (atype == "Function") {
                if (++funsize == 1) {//第一次出现function类型的参数，默认为回调方法
                    callback = arguments[i];
                }
                if (funsize == 2) {  //第二次出现的function类型的参数，视为错误处理方法
                    errorfun = arguments[i];
                }
            } else if (atype == "Object") {
                if (objsize == 0) {//第一次出现对象类型的参数
                    if (funsize > 0) {//出现过function类型的参数
                        opt = arguments[i];//该参数为配置项
                    } else {
                        data = arguments[i];//未出现过function则为交互数据
                        strsize++;
                    }
                }
            } else if (atype == "Number") {//参数类型为数字，为超时时间
                def.timeout = arguments[i];
            } else if (atype == "Boolean") {//参数类型为布尔型，改变为异步或同步
                def.diyAsync=arguments[i];
                def.async = arguments[i];
            }
        }
        var config = $.extend(def, opt);
        if(callback)config.async=true;//在没有处理成功返回函数时候，置同步处理
        url=Ladder.Service.parseUrl(url);//解析请求的路径的表达式
        if(!url){
            alert("对不起.没有访问服务路径");
            return;
        }
        //判断是跨域请求
        var _link=(location.href);
        _link=_link.substr(0,_link.indexOf("/",7));//当前页面url的域名
        if(url.indexOf("http")>-1){
            var _weblink=url.substr(0,url.indexOf("/",7));
            if (_link != _weblink && !Ladder.CrossDomain) {
                if (!/_@_$/.test(config.dataType)) {
                    config.dataType = "jsonp";
                    config.async = true;
                }
                if(!callback&&config.hasOwnProperty("diyAsync")&&!config.diyAsync){
                    alert("对不起，跨域访问，无法进行数据同步请求,请联系您的程序开发员");
                    return false;
                    //config.wait=true;//线程等待
                    //config.isResulthandle=false;//是否经过结果处理
                    //config.result=null;//返回的数据
                    //config.currentTime=new Date();
                }
            }
        }
        if(/(private=(\w*))|(ssl=(\w*))/.test(url)){
            var v = url.match(/(private=(\w*))|(ssl=(\w*))/);
            v=v[2]||v[4];
            if(v!=undefined&&v!="0"&& v.toLowerCase!=="false"){
                def.ssl=true;
            }
        }

        //处理参数中含有对象或者数组的情况
        var encrypt=[];
        if(Ladder.getType(data)=="Object"){
            if(!config.ssl&&data.hasOwnProperty("_s")){
                config.ssl=true;
            }
            var newObject={};
            for(var propname in data){
                var key=propname;
                var isAdd=false;
                if(/\$$/.test(propname)){
                    key=propname.replace(/\$$/,"");
                    encrypt.push(key);
                    isAdd=true;
                }
                if(!isAdd&&config.ssl){
                    encrypt.push(key);
                }
                if(/(Object)|(Array)/i.test(Ladder.getType(data[propname])))
                    newObject[key]=JSON.stringify(data[propname]);
                else  newObject[key]=data[propname];
            }
            data=newObject;
            if(encrypt.length>0){
                data["_p"]=Ladder.toString(encrypt,",");
                data["_t"]=Ladder.timestamp();
                if(!data["_s"])data["_s"]=Ladder.random();
                var enstr="";
                for(var i=0; i<encrypt.length;i++){
                    enstr+=data[encrypt[i]];
                }
                enstr=enstr+data["_p"]+data["_t"]+(window.UserKey||Ladder.getStore("UserKey")||Ladder.getCookie("UserKey"));
                data["token"]=Ladder.md5(enstr);
            }
        }

        //处理错误
        if(callback&&config.requestType == 'YF'&&!errorfun){
            errorfun=function(){
                callback({
                    statusCode:500,
                    message:"网络访问出现错误"
                });
            };
            config.hasErrorFun=false;
        }




        var xhr = $.ajax({
            cache: false,
            type: config.type,
            url: url,
            dataType: config.dataType.replace("_@_",''),
            data: data,
            async: config.async,
            success: handlesuccess,
            error: errorfun,
            timeout: config.timeout,
            beforeSend: config.elem ? function() { $(config.elem).loadover() } : config.onBefore,
            complete: config.elem ? function() { $(config.elem).unloadover() } : config.onComplete
        });
        //访问结果处理类
        function handlesuccess(re_data, xhe, tt) {
            if(config.wait){
                config.result=re_data;
                config.isResulthandle=true;
            }
            if (callback) {
                if (config.requestType == 'YF') {
                    re_data = Ladder.toJSON(re_data);
                    if (re_data.statusCode != 200) {
//                        if(re_data.statusCode==-401)alert(url);
                        if(config.assert&&Ladder.Service&&Ladder.Service.assertReply){
                            Ladder.Service.assertReply(re_data);
                        }
                        if (config.hasErrorFun)errorfun(re_data);
                        else callback(re_data, xhe, tt);
                    } else {
                        if (re_data.data &&/(^\{[\s\S]+\}$)|(^\[[\s\S]+\]$)/.test(re_data.data)) {
                            re_data.data = Ladder.toJSON(re_data.data);
                        }
                        callback(re_data, xhe, tt);
                    }
                } else {
                    callback(re_data, xhe, tt);
                }
            }
        }
        /* 线程同步代码
         while(config.wait && config.dataType=="jsonp" && !config.isResulthandle){
         $("<div></div>").delay(1000);
         var stime=(new Date()-config.currentTime);
         if(stime>config.timeout){
         break;
         }
         }
         if(config.wait && config.dataType=="jsonp" && config.isResulthandle){
         var re_data = Ladder.toJSON(config.result);
         if (re_data.statusCode != 200 && Ladder.Service&&Ladder.Service.assertReply) {
         Ladder.Service.assertReply(re_data);
         }
         return re_data;
         }
         */
        if(!config.async && config.requestType == 'YF'){
            var re_data = Ladder.toJSON(xhr.responseText);
            if (re_data.statusCode != 200 && Ladder.Service&&Ladder.Service.assertReply) {
                Ladder.Service.assertReply(re_data);
            }
            return re_data;
        }

        return xhr;
    };
    window.webajax=$.webajax;
    $.fn.webajax=function(url,data,callback,errorfun,opt){
        if(opt)opt.elem=this;else opt={elem:this};
        $.webajax(url,data,callback,errorfun,opt);
    };
    Ladder.webajax = webajax;
    Ladder.CrossDomain = false;
    //项目自定义访问服务
    Ladder.NS("Service");
    //web访问服务
    Ladder.Service = {
        assertReply:function(result) {
            var _type = Ladder.getType(result);
            switch (_type) {
                case "Object":{
                    if (result.hasOwnProperty("statusCode")) {
                        var redirecturl = false;
                        switch (result.statusCode * 1) {//判断登录状态
                            case -401://状态码为-401跳转到登录页面
                                redirecturl = URLS.URL_Login;
                                break;
                            case -402://状态码为-402跳转到错误页面
                                redirecturl = "/htmlpage/ErrorPage/error-402.html";
                                break;
                        }
                        if (redirecturl) {//控制跳转
                            if (window.parent) {
                                window.parent.window.location.href = YFLib.Service.parseUrl(redirecturl);
                            } else {
                                window.location.href = YFLib.Service.parseUrl(redirecturl);
                            }
                        }
                    }
                }
                    break;
                default:
                {

                }
                    break;
            }
        },
        /**
         * 交互请求
         * @param {String} url 请求路径
         * @param {function} fun 回调方法
         * @param {String,object} data 请求数据，如果是字符串类型默认为表名
         */
        request: function(url, fun, data) {
            if (url) {
                var requestUrl = url;
                requestUrl = requestUrl.replace("{webroot}", Ladder.BasicURL);
                if (data && Ladder.getType(data) == "String" && data.indexOf("=") < 0) {
                    data = { tableName: Tables[data] };
                }
                Ladder.webajax(requestUrl, data, fun, "post");
            } else {
                alert("请求参数不符合规则");
            }
        },
        /**
         * 解析路径
         * @param {String} url
         * @param {String} tkey 配置中的表键名
         * @returns {*}
         */
        parseUrl: function(url, tkey) {
            if (!url && !tkey)return false;
            var requestUrl = url;
            requestUrl = requestUrl.replace("{webroot}", Ladder.BasicURL);
            requestUrl = requestUrl.replace("{webserver}", URLS.URL_Server?URLS.URL_Server:URLS.URL_Root);
            if (!tkey)return requestUrl;
            if (Tables.hasOwnProperty(tkey)) {
                if (requestUrl.indexOf("?") > 0)requestUrl += "&";
                else requestUrl += "?";
                return requestUrl + "tableName=" + Tables[tkey];
            }
            return true;
        },
        /**
         * 设置请求信息,只清空action，url，backUrl，backParam，backAction，param，page，openway，title信息段，其他信息将保留
         * @param reqinfo 通常是Object,如果是String,则填充到URL段
         * @returns {Ladder.Service｝
         */
        setRequestInfo: function(reqinfo,isclear) {
            var df = { action: '', url: '', backUrl: '', backParam: '', backAction: '', param: '', page: '', openway: 0, title: '' };
            var requestinfo={};
            if(!isclear){
                requestinfo = store.get("requestinfo");
                if (requestinfo) {
                    requestinfo = JSON.parse(requestinfo);
                } else {
                    requestinfo ={};
                }
            }
            requestinfo = $.extend(requestinfo, df);
            if (!reqinfo) return Ladder.Service;
            if (Ladder.getType(reqinfo) == "String") {
                reqinfo = Ladder.Service.parseUrl(reqinfo);
                requestinfo.url = reqinfo;
                store.set("requestinfo", JSON.stringify(requestinfo));
                return Ladder.Service;
            }
            if (Ladder.getType(requestinfo) == "Object") {
                //if (!reqinfo.url) return Ladder.Service;
                if(reqinfo.url)reqinfo.url = Ladder.Service.parseUrl(reqinfo.url);
                requestinfo = $.extend(requestinfo, reqinfo);
                store.set("requestinfo", JSON.stringify(requestinfo));
                return Ladder.Service;
            }
            return Ladder.Service;
        },
        /**
         * 获取requestinfo，如果keep=true，数据保留，否则清空
         * @param keep false时将清空requestinfo存储的信息段,true时将进行保留
         * @returns {Object}
         */
        getRequestInfo: function (keep) {
            var requestinfo = store.get("requestinfo");
            if (!keep) {
                store.remove("requestinfo");
            }
            if (!requestinfo)return null;
            return JSON.parse(requestinfo);
        },
        /**
         * 页面跳转,根据requestinfo调到指定页面
         * @param w 窗口的宽度
         * @param h 窗口的高度
         * @param shade 窗口的阴影
         */
        gotoPage: function(w,h,shade) {
            var requestinfo=undefined;
            if(Ladder.getType(w)=="Object"){
                requestinfo = w;
                w=requestinfo.width;
                h=h||requestinfo.height;
                shade=shade||requestinfo.shade;
            }else{
                requestinfo = this.getRequestInfo(true);
            }
            if (!requestinfo.url)return;
            if(requestinfo.openway==undefined&&(w||h||shade))requestinfo.openway=2;
            if (window.parent && parent.Ladder && parent.Ladder.ui && w == undefined && h == undefined && shade == undefined) {
                parent.Ladder.ui.navtab.opentab(requestinfo);
            } else {
                switch (requestinfo.openway) {
                    case 0:
                        alert("对不起，系统框架不存在");
                        return;
                    case 1:
                        window.open(requestinfo.url);
                        return;
                    case 2:
                        if (!window.layer) {
                            alert("弹出层组件没有安装，请检查！！");
                            return;
                        }
                        var temp = Ladder.data(requestinfo);
                        w = (w == undefined ? temp.get("width") || temp.get("param.width") || Ladder.winWH().w : w);
                        h = (h == undefined ? temp.get("width") || temp.get("param.width") || Ladder.winWH().h : h);
                        shade = (shade == undefined ? 0.8 : shade);
                        layer.open({
                            type: 2,
                            title: requestinfo.title == undefined ? "欢迎使用本系统" : requestinfo.title,
                            shadeClose: true,
                            shade: shade,
                            area: [w + 'px', h + 'px'],
                            content: requestinfo.url //iframe的url
                        });
                        return;
                    case 3:
                        window.location.href = requestinfo.url;
                        break;
                    case 4:
                        if (window.parent.MainPage) {

                            try{
                                var iframes = $(window.parent.document).find("iframe");
                                var $pcontent=undefined;
                                for(var i=0,len=iframes.length;i<len;i++){
                                    if(iframes[i].contentDocument==document){
                                        $pcontent=$(iframes[i]);
                                    }
                                }
                                var pageinfo = {
                                    title: "操作页面",
                                    id: Ladder.uuid(),
                                    url: "",
                                    fromUrl: window.location.href,
                                    fromSrc: $pcontent ? $pcontent.attr("src") : "",
                                    fromID: $pcontent ? $pcontent.parent().attr("data-id") : "",
                                };
                                $.extend(pageinfo, requestinfo);
                                pageinfo.href = pageinfo.url;
                                delete pageinfo.link_url;
                                window.parent.MainPage.openPage(pageinfo);
                            } catch (error) {
                                window.parent.MainPage.openPage(requestinfo);
                            }


                        } else {
                            if (!window.layer) {
                                alert("未在系统框架打开");
                                return;
                            } else {
                                layer.msg("未在系统框架打开");
                            }
                        }
                        break;
                    default:
                        if (!window.layer) {
                            alert("未配置打开形式，请检查！！");
                            return;
                        } else {
                            layer.msg("未配置打开形式");
                        }
                }
            }
        }


    };
    //Ladder库附加扩展
    Ladder.store = store;//本地存储
    Ladder.template = laytpl;//数据模版
    Ladder.NS("tpl");
    /**
     * 快速模版方法
     * @param target  模版script标签 的ID或者是html文本
     * @param data   //引用的数据
     * @param ishtml {boolean}默认：false为$对象或者选择器,ture 直接解析html文本
     */
    Ladder.tpl=function(target,data,ishtml){
        if(!data)data=new Object();
        if(ishtml){
            return  laytpl(target).render(data);
        }else{
            var $el=$(target);
            if($el.length<1)return "";
            return  laytpl($el.html()).render(data);
        }
    };
    Ladder.fetchBasicURL = fetchBasicURL;
    /*以下为初始化执行方法*******************************************************************************************/
    if(!window.JSON)Ladder.include(require.toUrl("../vendor/json2.js"));
    //处理IE下没有console.log
    window.console = window.console || (function(){
            var c = {}; c.log = c.warn = c.debug = c.info = c.error = c.time = c.dir = c.profile
                = c.clear = c.exception = c.trace = c.assert = function(){};
            return c;
        })();
    //RequestAnimationFrame兼容行代码
    (function() {
        var lastTime = 0;
        var vendors = ['ms', 'moz', 'webkit', 'o'];
        for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
            window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
            window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
                || window[vendors[x]+'CancelRequestAnimationFrame'];
        }
        if (!window.requestAnimationFrame)
            window.requestAnimationFrame = function(callback) {
                var currTime = new Date().getTime();
                var timeToCall = Math.max(0, 16 - (currTime - lastTime));
                var id = window.setTimeout(function() { callback(currTime + timeToCall); },
                    timeToCall);
                lastTime = currTime + timeToCall;
                return id;
            };
        if (!window.cancelAnimationFrame)
            window.cancelAnimationFrame = function(id) {
                clearTimeout(id);
            };
    }());
    //jquery加载完成
    $(function(){
        $.fn.wresize = function( f ){
            var wresize = {fired: false, width: 0};
            function resizeOnce(){
                if (!-[1,]){
                    if ( ! wresize.fired ){wresize.fired = true;}
                    else{
                        var version = parseInt((Ladder.browserversion()+"'").replace(/[^0-9.]/ig,""), 10 );
                        wresize.fired = false;
                        if ( version < 7 ){return false;}
                        else if ( version == 7 ){
                            var width = $( window ).width();
                            if ( width != wresize.width ){ wresize.width = width;return false; }
                        }
                    }
                }
                return true;
            }
            function handleWResize( e ){if ( resizeOnce() ){return f.apply(this, [e]);}}
            this.each( function(){
                if ( this == window ){$( this ).resize( handleWResize );}
                else{$( this ).resize( f );}
            } );
            return this;
        };
    });
    Ladder.BasicURL = fetchBasicURL();
    window.YFLib = Ladder;
    window.ladder = Ladder;
    return Ladder;
}
	if(typeof define === "function" && define.amd){
		require.config({
		    paths: {
		        // "jquery": "../vendor/jquery-1.11.2.min",
		        "store":'../vendor/store.min',
		        'tpl': '../vendor/laytpl',
		        'severice':'../config/service',
		        'crypto':'../vendor/md5'
		    }
		});
		if(isHaveJq){
            define(['store', 'tpl', 'severice','crypto'],__functionForCore);
        }
        else{
            require.config({
                paths: {
                    "jquery": "../vendor/jquery-1.11.2.min"
                }
            });

            define(['store', 'tpl', 'severice','jquery','crypto'],__functionForCore);
            //define([(isHaveJq?undefined:'jquery'), 'store', 'tpl', 'severice','crypto'],__functionForCore);
        }

	}else{
		__functionForCore();
	}
})();


